package com.vcredit.creditcat.service.product.xrf;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.Header;
import org.apache.http.message.BasicHeader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.core.type.TypeReference;
import com.vcredit.creditcat.dto.product.CreditCRFAmountParamDto;
import com.vcredit.creditcat.enumtype.CRFAuditResultEnum;
import com.vcredit.creditcat.model.Cust;
import com.vcredit.creditcat.model.CustProductApply;
import com.vcredit.creditcat.service.CustProductApplyService;
import com.vcredit.creditcat.service.product.IProductApplyResultService;
import com.vcredit.creditcat.service.product.shared.ProductApplyServiceAdaptor;
import com.vcredit.creditcat.util.ConcurrentDateUtil;
import com.vcredit.creditcat.util.Encrypt;
import com.vcredit.creditcat.util.EnumExtUtil;
import com.vcredit.creditcat.util.HttpRequestExt;
import com.vcredit.framework.annotation.Log;
import com.vcredit.framework.util.JacksonUtil;

/**
 * 信而富申请实现类
 * 
 * @author zhaoqi01
 *
 */
@Service(ProductApplyServiceAdaptor.RESULT_BEANNAME_PREFIX + "25")
public class XRFApplyResultServiceImpl implements IProductApplyResultService {
	private static Logger logger = LoggerFactory.getLogger(XRFApplyResultServiceImpl.class);

	/** 对接用的url **/
	@Value("${crf.applay.url}")
	private String creditCrftestUrl;

	@Value("${crf.xinyongmao.dataSource}")
	private String dataSource;

	@Value("${crf.xinyongmao.key}")
	private String key;

	@Autowired
	private CustProductApplyService custProductApplyService;

	/**
	 * 查询接口
	 * 
	 * @param submitDto
	 * @return
	 * @throws Exception
	 */
	@Log
	public String Query(Object custId) throws Exception {
		Map<String, Object> resultMap = new HashMap<>();
		resultMap.put("orderId", "XYM_" + custId);

		String json = JacksonUtil.Obj2Json(resultMap);
		String signature = Encrypt.base64HmacMD5(key, json);
		logger.info("信而富查询json :" + json);
		signature = signature.replaceAll("\r\n", "");
		logger.info("signature :" + signature);
		try {
			Header[] headers = new Header[3];
			headers[0] = new BasicHeader("X-CrfChina-Signature", signature);
			headers[1] = new BasicHeader("X-Data-Source", dataSource);
			headers[2] = new BasicHeader("Content-Type", "application/json");
			String resultJson = HttpRequestExt.doPost(creditCrftestUrl.concat("/orderStatus"), json, "UTF-8", headers);
			return resultJson;
		} catch (Exception e) {
			logger.error("------------信而富查询出错!!", e);
			throw e;
		}
	}

	@Override
	public CustProductApply getProductApplyResult(Cust custs, long productId) throws Exception {
		CustProductApply custProductApply = new CustProductApply();
		custProductApply.setCustId(custs.getCustId());
		custProductApply.setProductId(productId);
		// TODO Auto-generated method stub
		// 如果不存在返回为空
		custProductApply = new CustProductApply();
		// 如果是提交成功 或者正在审批 或者没有回调的数据

		String resultJson = this.Query(custs.getCustId());
		CreditCRFAmountParamDto result = JacksonUtil.Json2Obj(resultJson, new TypeReference<CreditCRFAmountParamDto>() {
		});
		custProductApply.setCustId(custs.getCustId());
		custProductApply.setProductId(productId);
		custProductApply.setIsApply(false);
		CRFAuditResultEnum enumOnValue = EnumExtUtil.getEnumOnValue(CRFAuditResultEnum.class, result.getOrderState(), "key");

		switch (enumOnValue) {
		// 审核结果 0：已审批-失败；1：已审批-成功；2：审批中；3：未申请过；4：未申请过，认证条件齐全 5过渡条件
		case noneOrder:
			custProductApply.setAuditResult(3);
			break;
		case notpassOrder:
			custProductApply.setAuditResult(0);
			custProductApply.setIsApply(true);
			custProductApply.setCreditApplyTime(ConcurrentDateUtil.formatDateTime(ConcurrentDateUtil.addDayTime(new Date(), 30)));

			break;
		case applingOrder:
			custProductApply.setAuditResult(2);
			break;
		case throughOrder:
			custProductApply.setCreditExpiretime(ConcurrentDateUtil.formatDateTime(ConcurrentDateUtil.addDayTime(new Date(), 30)));
			custProductApply.setAuditResult(1);
		default:
			break;
		}
		custProductApply.setRejectMsg(enumOnValue.getDesc());
		custProductApply.setCustId(custs.getCustId());
		custProductApply.setAuditTime(ConcurrentDateUtil.formatDateTime(new Date()));
		return custProductApply;
	}
}
